package com.group.flagtivities;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;

public class FriendService extends Service {
	static final int REGISTER_CLIENT = 1;
	static final int UNREGISTER_CLIENT = 2;
	static final int REQUEST_FRIENDS = 3;
	
	ArrayList<Messenger> mClients = new ArrayList<Messenger>();
	final Messenger mMessenger = new Messenger(new IncomingHandler());

	private static String latestFriendResult;
	private static Timer timer;
	
	class IncomingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case REGISTER_CLIENT:
				mClients.add(msg.replyTo);
				sendFriends();
				break;
			case UNREGISTER_CLIENT:
				mClients.remove(msg.replyTo);
				break;
			case REQUEST_FRIENDS:
				forceUpdate();
				break;
			}
		}
	}
	
	private void forceUpdate() {
		String tempResult = WebUtil.retrieveFriends(Flagtivities.user_id);
		if (tempResult != null && !tempResult.equals(latestFriendResult)) {
			latestFriendResult = tempResult;
			sendFriends();
		}
		tempResult = null;
	}
	
	private TimerTask updateTask = new TimerTask() {
		@Override
		public void run() {
			try{
				forceUpdate();
			}catch(Exception e) {}
		}
	};
	
	private void sendFriends() {
		for (int i = mClients.size() - 1; i >= 0; i--) {
			try{
				Bundle b = new Bundle();
				b.putString("friends", latestFriendResult);
				Message msg = Message.obtain();
				msg.setData(b);
				mClients.get(i).send(msg);
			}catch(Exception e) {
				mClients.remove(i);
			}
		}
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return mMessenger.getBinder();
	}

	@Override
	public void onCreate() {
		super.onCreate();
				
		timer = new Timer();
		timer.schedule(updateTask, 0L, 60 * 1000L);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		timer.cancel();
		timer = null;
	}
}
